package myJs.en

import myJs.Utils
import myJs.Utils._
import myJs.myPkg.LayerOptions
import myJs.myPkg.jquery._
import myJs.tool.Tool
import myJs.tool.Tool._
import org.scalajs.dom.Event
import org.scalajs.dom.ext.Ajax
import shared.VarTool

import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import myJs.Implicits._

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("EnRegister")
object EnRegister {

  val count = 60

  @JSExport("init")
  def init = {

    bootStrapValidator

  }

  def refreshRemainTime(count: Int) = {
    Utils.mySetInterval(count, curCount => {
      $("#refreshButton").text(s"${messages("resend")}（" + curCount + "）").attr("disabled", true)
    }, () => {
      $("#refreshButton").text(messages("sendVerificationCode")).attr("disabled", false)
    }
    )
  }

  @JSExport("sendValidCode")
  def sendValidCode = {
    val phone = Tool.getInputByName("phone").myVal
    if (!phone.matches(VarTool.phoneRegexpStr)) {
      layer.msg(messages("pleaseEnterTheCorrectPhoneNumber"), LayerOptions.icon(5).time(3000))
      Tool.getInputByName("phone").focus()
    } else {
      refreshRemainTime(count)
      val url = g.jsRoutes.controllers.AppController.sendValidCode().url.toString
      val dict = js.Dictionary("phone" -> phone)
      val data = JSON.stringify(dict)
      Ajax.post(url = s"${url}", data = data, headers = Map("Content-Type" -> "application/json")).map { xhr =>
        val rs = xhr.responseText.toJDJAn
        val valid = rs("valid").toB
        if (!valid) {
          layer.msg(rs.myGet("message"), LayerOptions.icon(5).time(3000))
        }
      }
    }
  }

  def bootStrapValidator = {
    val url = g.jsRoutes.controllers.AppController.phoneCheck().url.toString
    val emailCheckUrl = g.jsRoutes.controllers.AppController.emailCheck().url.toString
    val maxNumber = Double.MaxValue
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "fullName" -> js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> "The user name is required"
            ),
          )
        ),
        "company" -> js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> "The institution is required"
            ),
          )
        ),
        "email" -> {
          val info = "The E-mail"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info} is required"
              ),
              "emailAddress" -> js.Dictionary(
                "message" -> s"${info} is invalid",
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${info} 	already existed",
                "url" -> emailCheckUrl,
                "delay" -> 1000,
                "type" -> "POST",
              ),
            )
          )
        },
        "password" -> {
          val info = s"The password"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info} is required"
              ),
              "identical" -> js.Dictionary(
                "message" -> "The password and confirm password are different",
                "field" -> "confirmPassword",
              ),
//              "regexp" -> js.Dictionary(
//                "message" -> "Must be composed of number or letter, contain uppercase and lowercase,at least 6 characters",
//                "regexp" -> js.RegExp("^(?=\\w*\\d)(?=\\w*[A-Z])(?=\\w*[a-z])[\\w]{6,}$"),
//              ),
            ),
          )
        },
        "confirmPassword" -> {
          val info = "The confirm password"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info} is required"
              ),
              "identical" -> js.Dictionary(
                "message" -> "The password and confirm password are different",
                "field" -> "password",
              ),
            ),
          )
        },
      )
    )
    $(s"#form").bootstrapValidator(dict).on("success.form.bv", (e: Event) => {
      e.preventDefault()
      val bv = $(s"#form").bv
      bv.defaultSubmit()
    })
  }


}
